<script setup lang="ts">
import { throttle } from 'lodash-es'
import { onMounted, onUnmounted, ref } from 'vue'
import { YkBabylonScene } from './create3D.ts'

const clientWidth = ref(window.innerWidth)
const clientHeight = ref(window.innerHeight)

const resizeObserver = new ResizeObserver(throttle(() => {
  /**
   * 在canvas大小改变时，自动重新渲染模型视野大小，如果不加该方法，则只是canvas大小变化，而模型会挤压变形，不能保持原模型实际的长宽比
   */
  try {
    clientWidth.value = canvas.value.clientWidth
    clientHeight.value = canvas.value.clientHeight
  } catch (e) {

  }
}, 500))

const canvas = ref()

let babylonScene: YkBabylonScene | null = null

onMounted(() => { // 组件加载后，初始化场景，在YkBabylonScene的构造函数中，会自动调用YkBabylonScene的CreateFrameScene方法，创建场景，并返回场景对象
  babylonScene = new YkBabylonScene(canvas.value)
  resizeObserver.observe(canvas.value)
})

onUnmounted(() => {
  // 停止监听 canvas 尺寸变化
  resizeObserver.disconnect()

  // 销毁 BabylonScene 实例及其资源
  if (babylonScene) {
    const { scene, engine } = babylonScene
    if (scene) {
      scene.dispose() // 释放场景资源
    }
    if (engine) {
      engine.dispose() // 释放引擎资源
    }
    babylonScene = null
  }
})
</script>

<template>
  <canvas ref="canvas" :width="clientWidth" :height="clientHeight" class="canvas"></canvas>
</template>

<style scoped>
.canvas {
  width: 100%;
  height: 100%;
}
</style>